package com.shop.cereshop.agent.service.product.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.agent.dao.product.AgentCartDAO;
import com.shop.cereshop.agent.page.product.CartVO;
import com.shop.cereshop.agent.page.product.SkuAttributeVO;
import com.shop.cereshop.agent.param.product.AgentCartDTO;
import com.shop.cereshop.agent.param.product.AgentCartSelectDTO;
import com.shop.cereshop.agent.service.product.AgentCartService;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.agentProduct.CereAgentCart;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.utils.EmptyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AgentCartServiceImpl implements AgentCartService {
  @Autowired
  private AgentCartDAO cartDAO;

  @Override
  public Integer addCart(AgentCartDTO agentCartDTO) {
    LocalDateTime now = LocalDateTime.now();
    CereAgentCart cereAgentCart = new CereAgentCart();
    BeanUtils.copyProperties(agentCartDTO, cereAgentCart);
    cereAgentCart.setSelected(IntegerEnum.YES.getCode());
    cereAgentCart.setCreateTime(now);
    cereAgentCart.setUpdateTime(now);
    return cartDAO.insert(cereAgentCart);
  }

  @Override
  public Integer deleteCart(List<Long> cartIds, Long agentUserId) {
    return cartDAO.deleteBatchIdsByAgentUserId(cartIds);
  }

  @Override
  public Page<CartVO> listCart(AgentCartSelectDTO agentCartSelectDTO) {
    PageHelper.startPage(agentCartSelectDTO.getPage(), agentCartSelectDTO.getPageSize());
    List<CartVO> cartVOList = cartDAO.selectCarts(agentCartSelectDTO.getAgentUserId());
    // 查询每个购物车的规格属性
    if (!EmptyUtils.isEmpty(cartVOList)) {
      cartVOList.forEach(cartVO -> {
        if (cartVO.getSkuId() != null) {
          List<SkuAttributeVO> specs = cartDAO.selectCartSpecs(cartVO.getSkuId());
          cartVO.setSpecs(specs);
        }
      });
    }
    PageInfo<CartVO> cartVOPageInfo = new PageInfo<>(cartVOList);
    return new Page<>(cartVOPageInfo.getList(), cartVOPageInfo.getTotal());
  }

  @Override
  public Integer updateCart(AgentCartDTO agentCartDTO) {
    CereAgentCart cereAgentCart = new CereAgentCart();
    BeanUtils.copyProperties(agentCartDTO, cereAgentCart);
    cereAgentCart.setUpdateTime(LocalDateTime.now());
    return cartDAO.updateById(cereAgentCart);
  }
}
